import React, { useEffect } from 'react'
import { Form, Input, Button, Checkbox } from 'antd'
import { ILoginParams } from './types'

import './style.less'
import { useDispatch } from 'react-redux'
import { actionFecthLogin } from './store/actions'
import { useNavigate } from 'react-router-dom'

const Login: React.FC = () => {
  const [form] = Form.useForm()
  const dispatch = useDispatch()
  const navgiate = useNavigate()
  useEffect(() => {
    form.setFieldsValue({
      code: '246810',
      isAgree: true,
      mobile: '13911111111',
    })
  }, [])
  const handleFinish = (val: ILoginParams) => {
    dispatch(actionFecthLogin(val, navgiate))
  }
  const handleReset = () => {
    form.resetFields()
  }
  return (
    <div className="login-form-wrap flex-3">
      <Form form={form} onFinish={handleFinish}>
        <Form.Item
          name="mobile"
          label="手机号"
          rules={[{ required: true, message: '手机号' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          name="code"
          label="验证码"
          rules={[{ required: true, message: 'code' }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          name="remember"
          valuePropName="checked"
          wrapperCol={{ offset: 8, span: 16 }}
          rules={[
            {
              validator: (_, val) => {
                return val
                  ? Promise.resolve()
                  : Promise.reject(new Error('你没同意'))
              },
            },
          ]}
        >
          <Checkbox>Remember me</Checkbox>
        </Form.Item>

        <Form.Item
          name="isAgree"
          valuePropName="checked"
          wrapperCol={{ offset: 8, span: 16 }}
        >
          <Checkbox>isAgree</Checkbox>
        </Form.Item>
        <Form.Item
          name="password"
          label="密码1"
          rules={[{ required: true, message: 'password' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          name="password2"
          label="密码2"
          rules={[
            { required: true, message: '不能为空' },
            {
              validator: (_, val) => {
                if (val && form.getFieldValue('password') === val) {
                  return Promise.resolve()
                }
                return Promise.reject(new Error('两次密码不一致'))
              },
            },
          ]}
        >
          <Input />
        </Form.Item>

        <Form.Item>
          <Button type="primary" htmlType="submit">
            Submit
          </Button>
          <Button htmlType="button" onClick={handleReset}>
            Reset
          </Button>
        </Form.Item>
      </Form>
    </div>
  )
}

export default Login
